<route lang="json">
{
  "meta": {
    "title": "t('juZhenKaiQi')"
  }
}
</route>
<script setup lang="ts" name="openMatrix">
import { useRpopupPickerRef } from "@@/components/rework/RpopupPicker";
import useBalanceStore, { StoreCoinItem } from "@@/store/useBalanceStore";
import { fixedDecimals } from "@@/utils/tools/format";
import { addCache } from "@@/hooks/routeCache";
import { _require } from "@@/utils/tools";
import router from "@@/router";
import useTabPageStore from "@@/store/useTabPageStore";
import {
  apiCheckFee,
  CheckFee,
  apiOpenAmount,
  OpenAmount,
} from "@@/api/transaction/index";
import { apiFeeTxid, apiOpenMatrixTxid } from "@@/api/transaction/submitTxid";
import { sdkTransfer, sdkTransferToken, sdkSign } from "@@/sdk/web3Eth";
import { toast } from "@@/hooks/vantHooks";
import throttle from "lodash/throttle";
import logs from "./components/logs.vue";
import { sysLoad } from "@@/hooks/sysHooks";
import { useInterval } from "@@/hooks/toolsHooks";

addCache("openMatrix");

const balanceStore = useBalanceStore();
const tabPageStore = useTabPageStore();

const pickerData = computed<StoreCoinItem[]>(
  () =>
    Object.values(balanceStore.ethCoinEnum).filter((v) =>
      [tabPageStore.homeData?.storage_coin.id].includes(v?.id)
    ) as any
);

const RpopupPickerRef = useRpopupPickerRef<StoreCoinItem>();
onMounted(() => {
  watch(
    () => RpopupPickerRef.value?.elect,
    (newVal, oldVal) => {
      if (newVal?.id === oldVal?.id) return;
      changeCoin(newVal);
    },
    {
      deep: true,
    }
  );
});
function changeCoin(coin: StoreCoinItem | undefined) {
  balanceStore.findBalance(coin);
}
sysLoad(() => changeCoin(electCoin.value));

const electCoin = computed(
  () => balanceStore.ethCoinEnum[RpopupPickerRef.value?.elect?.id!]
);

const amountSelect = computed(() =>
  Object.values({ ...tabPageStore.homeData?.store })
);

const { t } = useI18n();
const form = reactive({
  amount: "",
});
const loading = reactive({
  onSubmit: false,
  onPayFee: false,
  getCheckFee: false,
});
const checkFee = ref<CheckFee.Res>();
const getCheckFee = throttle(
  async () => {
    loading.getCheckFee = true;
    checkFee.value = await apiCheckFee();
    loading.getCheckFee = false;
    if (checkFee.value.fee == 1) intervalRefresh.close();
  },
  1500,
  { leading: true, trailing: true }
);
const openAmount = ref<OpenAmount.Res>();
async function getOpenAmount() {
  openAmount.value = await apiOpenAmount();
  form.amount = openAmount.value?.amount.toString() || "";
}
const intervalRefresh = useInterval(refresh, 2000, {
  setupOpen: false,
  activatedOpen: false,
});
async function onPayFee() {
  if (!tabPageStore.homeData) return tabPageStore.getHomeData();
  const number = Number(tabPageStore.homeData.bnb_fee);
  const address = tabPageStore.homeData?.address.storage_address;
  // loading.onPayFee = true;
  // const sign = await sdkSign("pay fee");
  // loading.onPayFee = false;
  // if (!sign.status) return;
  loading.onPayFee = true;
  toast.loading(t("jiaoYiZhongQingBuYaoTuiChu"));
  const res = await sdkTransfer(number, 18, address);
  toast.close();
  loading.onPayFee = false;
  if (!res.status) return toast.error(res.message);
  const verify = await apiFeeTxid({ txid: res.data!, number });
  if (verify) {
    form.amount = openAmount.value?.amount.toString() || "";
    payFeeed.value = true;
    intervalRefresh.open();
  }
}

function refresh() {
  getCheckFee();
  logsRef.value?.refresh();
}

async function onSubmit() {
  const amount = Number(form.amount);
  const coin = electCoin.value;
  const address = tabPageStore.homeData?.address.storage_address!;
  if (!coin) return toast.text(t("qingXuanZeBiZhong"));
  // loading.onPayFee = true;
  // const sign = await sdkSign("pay open matrix");
  // loading.onPayFee = false;
  // if (!sign.status) return;
  loading.onSubmit = true;
  toast.loading(t("jiaoYiZhongQingBuYaoTuiChu"));
  const res = await sdkTransferToken(
    coin.contract_addr!,
    amount,
    coin.format,
    address
  );
  toast.close();
  loading.onSubmit = false;
  if (!res.status) return toast.error(res.message);
  const verify = await apiOpenMatrixTxid({ number: amount, txid: res.data! });
  if (verify) submited.value = true;
  logsRef.value?.refresh();
}
getCheckFee();
getOpenAmount();
tabPageStore.getHomeData();
const submited = ref(false);
const payFeeed = ref(false);
const logsRef = ref<InstanceType<typeof logs>>();
const colors = [
  "#cc3",
  "#cc3",
  "#3CCBDE",
  "#3CCBDE",
  "#3CCBDE",
  "#3CCBDE",
  "#e33",
  "#e33",
  "#e33",
  "#e33",
  "#e33",
  "#e33",
  "#e33",
  "#e33",
];
</script>

<template>
  <CpageView>
    <div class="auto-MT-md">
      <Ccard class="clip-path-1 flex-J-SB flex-A-C Pcol-sm" bg="var(--C-M1-O1)">
        <div>{{ $t("zhuWang") }}</div>
        <div>BNB SMart Chain (BEP20)</div>
      </Ccard>
      <Bcard1>
        <div class="flex-J-SB">
          <RpopupPicker
            class="flex-A-C"
            ref="RpopupPickerRef"
            :picker-data="pickerData"
          >
            <template #left-content>
              <Rimage size="42rem" :src="RpopupPickerRef?.elect?.logo" />
              <div class="ML-xs">{{ RpopupPickerRef?.elect?.code }}</div>
            </template>
            <template #option="{ code, logo }: StoreCoinItem">
              <div class="flex-A-C flex-J-SB" style="width: 5em">
                <Rimage size="42rem" :src="logo" />
                <div class="T-A-C" style="width: 3em">{{ code }}</div>
              </div>
            </template>
          </RpopupPicker>
          <div class="T-S-sm">
            {{ $t("yue") }}{{ fixedDecimals(electCoin?.balance, 4) }}
          </div>
        </div>
        <Ccard bg="var(--C-M1-O1)" class="clip-path-1 MT-md PD-sm auto-MT-sm">
          <Rinput readonly :model-value="form.amount" type="number" />
          <VanDivider />
          <RradioBtnGroup v-model="form.amount">
            <RradioBtn
              :value="item"
              :disabled="
                !openAmount?.max ||
                +item > +openAmount?.max ||
                +item < +openAmount.amount
              "
              :active-bg="colors[i]"
              :active-border-color="colors[i]"
              :style="{ border: `${colors[i]} 1rem solid` }"
              class="cls1 R-0"
              :class="{
                'B-M1': i < Number(tabPageStore.homeData?.user_info.level),
              }"
              v-for="(item, i) in amountSelect"
            >
              {{ item }}
            </RradioBtn>
          </RradioBtnGroup>
        </Ccard>
        <div class="C-fail T-S-sm MT-sm">
          {{ $t("meiGeZhangHaoZhiNengKaiQiYiCi") }}
        </div>
      </Bcard1>
      <Rbutton
        v-if="submited || Number(tabPageStore.homeData?.user_info.level) != 0"
        :disabled="true"
        class="MT-md clip-path-1"
        style="color: #ff0"
        :size="'large'"
        bg="var(--C-M1)"
      >
        {{ $t("yiKaiQi") }}
      </Rbutton>
      <Rbutton
        v-else-if="!checkFee?.fee || checkFee?.fee == 2"
        @click="onPayFee"
        :loading="loading.onPayFee"
        :disabled="payFeeed"
        class="MT-md clip-path-1"
        style="color: #ff0"
        :size="'large'"
        bg="var(--C-M1)"
      >
        {{ $t("zhiFuShouXuFei") }}({{ tabPageStore.homeData?.bnb_fee }} BNB)
      </Rbutton>
      <Rbutton
        v-else-if="checkFee.fee == 0"
        @click="getCheckFee"
        :loading="loading.onPayFee"
        class="MT-md clip-path-1"
        :size="'large'"
        bg="var(--C-M1)"
      >
        {{ $t("shuaXinQuKuaiQueRenZhong") }}
      </Rbutton>
      <Rbutton
        v-else-if="checkFee.fee == 1"
        @click="onSubmit"
        :loading="loading.onSubmit"
        class="MT-md clip-path-1"
        style="color: #ff0"
        :size="'large'"
        bg="var(--C-M1)"
      >
        {{ $t("juZhenKaiQi") }}
      </Rbutton>
      <VanDivider class="C-M1">{{ $t("chongZhiJiLu") }}</VanDivider>
      <logs ref="logsRef" />
    </div>
  </CpageView>
</template>

<style lang="scss" scoped>
.cls1 {
  font-size: var(--T-S-sm);
  border: 1rem solid var(--C-T1-O1);
}
</style>
